﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;

namespace eTMS.Controls
{
    /// <summary>
    /// Summary description for UserControl1.
    /// </summary>
    public class NumberTextBox : eTMS.Controls.TextBox
    {

        public string Spelling
        {
            get { return ReadNumBer(); }
        }
        public enum NumBerMode
        {
            Int, Double
        }
        private NumBerMode mode = NumBerMode.Int;
        public NumBerMode Mode
        {
            get
            {
                return mode;
            }
            set
            {
                mode = value;
            }
        }
        protected string ReadSmallNumBer(string s, string[] donvi, bool readzero)
        {
            double d = 0;
            try
            {
                d = Convert.ToDouble(s);
            }
            catch
            {
                d = 0;
            }
            string strTmp = d.ToString();
            string strResult = "";
            if (readzero)
            {
                for (int i = 0; i < s.Length - d.ToString().Length; i++)
                {
                    strResult += "không ";
                }
            }
            if (strTmp.Length == 3)
            {
                int i = Convert.ToInt32(strTmp[0].ToString());
                int j = Convert.ToInt32(strTmp.Substring(1, 2));
                strResult += donvi[i].ToString() + " trăm";
                if ((j < 10) && (j > 0))
                    strResult += " linh " + ReadSmallNumBer(strTmp.Substring(1, strTmp.Length - 1), donvi, readzero);
                else
                    strResult += " " + ReadSmallNumBer(strTmp.Substring(1, strTmp.Length - 1), donvi, readzero);
            }
            if (strTmp.Length == 2)
            {
                int i = Convert.ToInt32(strTmp[0].ToString());
                int j = Convert.ToInt32(strTmp[1].ToString());
                string hangchuc = donvi[i].ToString();
                string hangdv = donvi[j].ToString();
                if (i == 1)
                {
                    hangchuc = " mười ";
                    if (j == 5) hangdv = " lăm ";
                    if (j == 0) hangdv = " ";
                }
                else
                {
                    if (j == 4) hangdv = " tư ";
                    if (j == 5) hangdv = " lăm ";
                    if (j == 0) hangdv = " ";
                    hangchuc = donvi[i] + " mươi ";
                }
                strResult += hangchuc + " " + hangdv;
            }
            if (strTmp.Length == 1)
            {
                int i = Convert.ToInt32(strTmp[0].ToString());
                string hangdv = donvi[i].ToString();
                if (i == 0) hangdv = " ";
                strResult += hangdv;
            }
            return strResult;
        }
        protected string ReadNumBer()
        {
            return ReadNumBer(this.Text, false);
        }
        private string ReadNumBer(string numberText, bool readzero)
        {
            string dot = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
            string nstrGroup = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator;
            string[] donvi ={ "không", "một", "hai", "ba", "bốn", "năm", "sáu", "bẩy", "tám", "chín" };
            string[] hang ={ "", "nghìn", "triệu", "tỷ", "nghìn tỷ", "triệu tỷ", "tỷ tỷ", "nghìn tỷ tỷ" };
            string sS = numberText;
            if (sS.Trim() == "") return "";
            string strResult = "";
            if (sS.Substring(0, 1) == "-")
            {
                strResult = "Âm ";
                sS = sS.Substring(1, sS.Length - 1);
            }
            if (mode == NumBerMode.Double)
            {
                if (sS.IndexOf(dot) > 0)
                {
                    string[] arrs = sS.Split(dot.ToCharArray());
                    return ReadNumBer(arrs[0], false) + " phẩy " + ReadNumBer(arrs[1], true);
                }
            }

            string[] strTmp = sS.Split(nstrGroup.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            int ih = 0;
            ih = strTmp.Length;
            for (int i = 0; i < strTmp.Length; i++)
            {
                string s1 = ReadSmallNumBer(strTmp[i], donvi, readzero);
                ih--;
                if (s1.Trim() != "")
                {
                    if ((i == strTmp.Length - 1) && (Convert.ToInt32(strTmp[i]) < 10) && (strResult.Trim() != ""))
                    {
                        strResult += " lẻ " + s1;
                    }
                    else
                    {
                        strResult += " " + s1 + " " + hang[ih];
                    }

                }
            }
            strResult = strResult.Trim();
            while (strResult.IndexOf("  ") > 0) strResult = strResult.Replace("  ", " ");
            if (strResult.Trim() == "") return "";
            if ((strResult.IndexOf("Âm ") < 0) && !readzero) strResult = strResult[0].ToString().ToUpper() + strResult.Substring(1, strResult.Length - 1);

            return strResult;
        }
        private bool btextvalidated = false;
        public string SplitCharacter = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator;
        public NumberTextBox()
        {
            this.TextAlign = HorizontalAlignment.Right;
        }
        private double string2double(string str)
        {
            double d;
            try
            {
                d = Convert.ToDouble(str.Trim().Replace(this.SplitCharacter, ""));
            }
            catch
            {
                d = 0;
            }
            return d;
        }
        public double Value
        {
            get
            {
                return string2double(this.Text);
            }
            set
            {
                btextvalidated = true;
                if (value != 0)
                {
                    this.Text = FormatText(value.ToString());
                }
                else
                {
                    this.Text = "0";
                }

                btextvalidated = false;
            }
        }
        private ToolTip t = new ToolTip();

        protected override void OnValidated(EventArgs e)
        {
            double d = this.Value;
            if (d != 0)
            {
                this.Text = FormatText(d.ToString());
            }
            else
            {
                this.Text = "0";
            }
            if (!this.ReadOnly) this.BackColor = Color.FromArgb(255, 255, 255);

            base.OnValidated(e);
        }
        private string Invertstring(string strin)
        {
            string strout = "";
            for (int i = strin.Length - 1; i >= 0; i--)
                strout += strin[i];
            return strout;
        }
        private string FormatText(string strin)
        {
            if (mode == NumBerMode.Double)
            {
                if (strin.IndexOf(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator) > 0)
                {
                    string[] arrstrout = strin.Split(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    if (arrstrout[1].Trim() == "") return string.Format("{0:N0}", string2double(arrstrout[0])).Replace(",", SplitCharacter) + System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
                    if (arrstrout[0].Trim() == "")
                        return "0." + Invertstring(string.Format("{0:N0}", string2double(Invertstring(arrstrout[1])))).Replace(",", SplitCharacter);
                    if (arrstrout[0][0] == '-')
                        return "-" + string.Format("{0:N0}", string2double(arrstrout[0])).Replace(",", SplitCharacter) + "." + Invertstring(string.Format("{0:N0}", string2double(Invertstring(arrstrout[1]))));
                    else
                        return string.Format("{0:N0}", string2double(arrstrout[0])).Replace(",", SplitCharacter) + "." + Invertstring(string.Format("{0:N0}", string2double(Invertstring(arrstrout[1]))));
                }
            }
            return string.Format("{0:N0}", Convert.ToDouble(strin.Replace(SplitCharacter, ""))).Replace(",", SplitCharacter);
        }
        protected override void OnTextChanged(EventArgs e)
        {
            if (!btextvalidated)
            {
                btextvalidated = true;
                bool hasdot = false;
                int indexOfDot = this.Text.IndexOf(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
                if (!eTMS.Commons.Common.IsNumber(this.Text)) return;
                if (mode == NumBerMode.Double)
                {
                    if (this.Text.Length > 0)
                    {
                        if (indexOfDot == this.Text.Length - 1)
                        {
                            hasdot = true;
                        }
                    }
                }
                int curselection = this.SelectionStart;
                int currlength = this.Text.Length;
                double d = eTMS.Commons.Common.String2Double(this.Text);
                string text = FormatText(d.ToString());
                
                if ((indexOfDot > 0) && (mode == NumBerMode.Double))
                {
                    int start= -1;
                    for (int i = this.Text.Length - 1; i >= indexOfDot; i--)
                    {
                        if ((this.Text[i] != '0') && (this.Text[i] != System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]))
                        {
                            break;
                        }
                        start = i ;
                    }
                    if (start > 0)
                    {
                        for (int i =start; i<this.Text.Length; i++)
                        {
                            text += this.Text[i];
                        }
                    }
                }
                this.Text = text;
                try
                {
                    this.SelectionStart = curselection + this.Text.Length - currlength;
                }
                catch
                {
                }
                this.SelectionLength = 0;

            }
            btextvalidated = false;
            base.OnTextChanged(e);
        }
        protected override void OnMouseHover(EventArgs e)
        {
            base.OnMouseHover(e);
            t.SetToolTip(this, ReadNumBer());

        }

    }
}
